<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <style type="text/css">
        body {
            width: 1200px;
        }
    </style>
</head>
<body>
<div>
    <hr>
    您的姓名:<input type="text" id="username">
    <hr>
    <button onclick="build()">建立连接</button>
</div>
<hr>
<div>
    发送给:<input type="text" id="tousername">
</div>
<hr>
<div>
    <textarea rows="10" cols="100" id="content">
    </textarea>
    <br> <br>
    <button onclick="send()">发送</button>
</div>

<div id="showMessage"></div>
<script>
    var websocket = null;

    function build() {
        var username = $("#username").val();
        if ('WebSocket' in window) {
            websocket = new WebSocket(
                "ws://localhost:8080/websocket/" + username);
            //连接成功建立的回调方法
            websocket.onopen = function () {
                $("#showMessage").append("<p color='red'>build success!</p>");
                $("#tousername").append("<option>" + username + "</option>");
            }
            //连接发生错误的回调方法
            websocket.onerror = function () {
                alert("登录失败");
            };
            //连接关闭的回调方法
            websocket.onclose = function () {
                $("#showMessage").html("连接关闭");
            };
            //接收到消息的回调方法
            websocket.onmessage = function (e) {
                var jsonObject = JSON.parse(e.data);
                $("#showMessage").append("<p>" + jsonObject.from + "对" + jsonObject.to + "说:" + jsonObject.content + "</p>");
            };
        } else
            alert("Not Support!");
    }

    window.onbeforeunload = function () {
        if (null != websocket)
            websocket.close();
    };

    function send() {
        var username = $("#username").val();
        var content = $("#content").val();
        var tousername = $("#tousername").val();
        var mes = {
            "from": username,
            "to": tousername,
            "content": content
        };
        if (null != websocket)
            websocket.send(JSON.stringify(mes));
    }
</script>
</body>
</html>